#include "ServerSocket.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <errno.h>
#include <unistd.h>
#include "Socket.h"

ServerSocket::ServerSocket()
{
}

ServerSocket::~ServerSocket()
{
}

int ServerSocket::Init()
{
	SetHandler(socket(AF_INET, SOCK_STREAM, 0));	// Only IPv4
	if(GetHandler() != -1)
		return 0;
	else
		return errno;
}

int ServerSocket::Bind(int port)
{
	sockaddr_in saddr = {0};
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(port);
	saddr.sin_addr.s_addr = 0x00000000;	// any address (0.0.0.0)
	errno = 0;
	if(bind(GetHandler(), reinterpret_cast<sockaddr*>(&saddr), sizeof(saddr)) != 0)
		return errno;
	else
		return 0;
}

int ServerSocket::Listen()
{
	if(listen(GetHandler(), 5) != 0)
		return errno;
	else
		return 0;
}

int ServerSocket::Accept(Socket& sock)
{
	int s = accept(GetHandler(), NULL, NULL);
	if(s != -1)
	{
		sock.Init(s);
		return 0;
	}
	else
		return errno;
}
